const { getUserById, getUserFavorites, addFavorite, deleteFavorite, getGasCardById, rechargeGasCard, getRechargeRecords, getUserCoupons, receiveCoupon, getCouponUsageRecords, getRecommendationQRCode, getRecommendationRecords, submitMerchantApplication, getMerchantApplicationStatus, getUserOrders, getOrderDetail, cancelOrder, confirmReceipt } = require('../models/User');
const pool = require('../config/db');

// 获取用户信息
const getUserProfile = async (req, res) => {
    console.log('[USER] 开始获取用户信息', { userId: req.user.userId });
    try {
        if (!req.user || !req.user.userId) {
            console.error('[USER] 缺少用户ID');
            return res.status(400).json({
                code: 400,
                message: '缺少用户ID'
            });
        }

        const user = await getUserById(req.user.userId);
        if (!user) {
            console.warn('[USER] 用户不存在', { userId: req.user.userId });
            return res.status(404).json({
                code: 404,
                message: '用户不存在'
            });
        }

        console.log('[USER] 用户信息获取成功', { userId: user.id });
        res.json({
            code: 200,
            message: '获取成功',
            data: {
                id: user.id,
                userId: user.userId,
                nickname: user.nickname || '',
                avatar: user.avatar || '',
                gasCardBalance: user.gasCardBalance || 0,
                phone: user.phone || '',
                email: user.email || '',
                role: user.role || 'user',
                realName: user.realName || ''
            }
        });
    } catch (error) {
        console.error('[USER] 获取用户信息失败', { 
            userId: req.user?.userId, 
            error: error.message,
            stack: error.stack
        });
        res.status(500).json({
            code: 500,
            message: '获取用户信息失败',
            error: error.message
        });
    }
};

// 获取我的收藏
const getMyFavorites = async (req, res) => {
    console.log('[USER] 开始获取用户收藏', { userId: req.user.userId });
    try {
        const favorites = await getUserFavorites(req.user.userId);
        console.log('[USER] 用户收藏获取成功', { userId: req.user.userId, count: favorites.length });
        res.json({
            code: 200,
            data: favorites
        });
    } catch (error) {
        console.error('[USER] 获取收藏列表失败', { userId: req.user.userId, error: error.message });
        res.status(500).json({
            code: 500,
            message: '获取收藏列表失败'
        });
    }
};

// 收藏店铺
const createFavorite = async (req, res) => {
    console.log('[USER] 开始收藏店铺', { userId: req.user.userId, storeId: req.body.storeId });
    try {
        const { storeId } = req.body;
        if (!storeId) {
            console.warn('[USER] 收藏店铺失败: 缺少店铺ID', { userId: req.user.userId });
        return res.status(400).json({
                code: 400,
                message: '缺少店铺ID'
            });
        }
        await addFavorite(req.user.userId, storeId);
        console.log('[USER] 店铺收藏成功', { userId: req.user.userId, storeId });
        res.json({
            code: 200,
            message: '收藏成功'
        });
    } catch (error) {
        console.error(error);
        if (error.message === '已收藏该店铺') {
            return res.status(400).json({
                code: 400,
                message: error.message
            });
        }
        res.status(500).json({
            code: 500,
            message: '收藏失败'
        });
    }
};

const updateUserProfile = async (req, res) => {
    console.log('[USER] 开始更新用户信息', { userId: req.user.userId, updateData: req.body });
    try {
        const { nickname, avatar, phone } = req.body;
        const userId = req.user.userId;

        // 构建更新字段和参数
        const updates = [];
        const params = [];
        if (nickname !== undefined) {
            updates.push('nickname = ?');
            params.push(nickname);
        }
        if (avatar !== undefined) {
            updates.push('avatar = ?');
            params.push(avatar);
        }
        if (phone !== undefined) {
            updates.push('phone = ?');
            params.push(phone);
        }

        if (updates.length === 0) {
            console.warn('[USER] 未提供更新字段', { userId });
        return res.status(400).json({ code: 400, message: '没有需要更新的字段' });
        }

        params.push(userId);
        await pool.execute(`UPDATE users SET ${updates.join(', ')} WHERE id = ?`, params);
        const updatedUser = await getUserById(userId);

        console.log('[USER] 用户信息更新成功', { userId: updateduser.userId });
        res.json({
            code: 200,
            message: '更新成功',
            data: {
                id: updateduser.userId,
                nickname: updatedUser.nickname,
                avatar: updatedUser.avatar
            }
        });
    } catch (error) {
        console.error('[USER] 用户信息更新失败', { userId, error: error.message });
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 获取加油卡信息
const getGasCardInfo = async (req, res) => {
    console.log('[USER] 开始获取加油卡信息', { userId: req.user.userId });
    try {
        const gasCard = await getGasCardById(req.user.userId);
        if (!gasCard) {
            console.warn('[USER] 加油卡不存在', { userId: req.user.userId });
        return res.status(404).json({ code: 404, message: '加油卡不存在' });
        }
        console.log('[USER] 加油卡信息获取成功', { userId: req.user.userId, balance: gasCard.balance });
        res.json({
            code: 200,
            data: gasCard
        });
    } catch (error) {
        console.error('[USER] 加油卡信息获取失败', { userId: req.user.userId, error: error.message });
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 加油卡充值
const handleRechargeGasCard = async (req, res) => {
    console.log('[USER] 开始加油卡充值', { userId: req.user.userId, amount: req.body.amount, paymentMethod: req.body.paymentMethod });
    try {
        const { amount, paymentMethod } = req.body;
        if (!amount || !paymentMethod) {
            console.warn('[USER] 充值参数不完整', { userId: req.user.userId, hasAmount: !!amount, hasPaymentMethod: !!paymentMethod });
        return res.status(400).json({ code: 400, message: '缺少必要参数' });
        }
        const result = await rechargeGasCard(req.user.userId, amount, paymentMethod);
        const user = await getUserById(req.user.userId);
        console.log('[USER] 加油卡充值成功', { userId: req.user.userId, newBalance: user.gas_card_balance, transactionId: result.transactionId });
        res.json({
            code: 200,
            message: '充值成功',
            data: {
                balance: user.gas_card_balance,
                transactionId: result.transactionId
            }
        });
    } catch (error) {
        console.error('[USER] 加油卡充值失败', { userId: req.user.userId, amount, error: error.message });
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 获取充值记录
const handleGetRechargeRecords = async (req, res) => {
    console.log('[USER] 获取充值记录', { userId: req.user.userId, page: req.query.page, size: req.query.size });
    try {
        const { page = 1, size = 10 } = req.query;
        const records = await getRechargeRecords(req.user.userId, parseInt(page), parseInt(size));
        console.log('[USER] 充值记录获取成功', { userId: req.user.userId, page, size, total: records.length });
        res.json({
            code: 200,
            data: records
        });
    } catch (error) {
        console.error('[USER] 充值记录获取失败', { userId: req.user.userId, error: error.message });
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 获取用户优惠券
const handleGetUserCoupons = async (req, res) => {
    console.log('[USER] 获取用户优惠券', { userId: req.user.userId });
    try {
        const coupons = await getUserCoupons(req.user.userId);
        console.log('[USER] 优惠券获取成功', { userId: req.user.userId, count: coupons.length });
        res.json({
            code: 200,
            data: coupons
        });
    } catch (error) {
        console.error('[USER] 优惠券获取失败', { userId: req.user.userId, error: error.message });
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 领取优惠券
const handleReceiveCoupon = async (req, res) => {
    console.log('[USER] 领取优惠券', { userId: req.user.userId, couponId: req.body.couponId });
    try {
        const { couponId } = req.body;
        if (!couponId) {
            console.warn('[USER] 缺少优惠券ID', { userId: req.user.userId });
        return res.status(400).json({ code: 400, message: '缺少优惠券ID' });
        }
        const result = await receiveCoupon(req.user.userId, couponId);
        res.json({
            code: 200,
            message: '领取成功',
            data: result
        });
    } catch (error) {
        console.error('领取优惠券失败:', error);
        res.status(400).json({ code: 400, message: error.message });
    }
};

// 获取优惠券使用记录
const handleGetCouponUsageRecords = async (req, res) => {
    try {
        const records = await getCouponUsageRecords(req.user.userId);
        res.json({
            code: 200,
            data: records
        });
    } catch (error) {
        console.error('获取优惠券使用记录失败:', error);
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 获取推荐二维码
const handleGetRecommendationQRCode = async (req, res) => {
    try {
        const result = await getRecommendationQRCode(req.user.userId);
        res.json({
            code: 200,
            data: result
        });
    } catch (error) {
        console.error('获取推荐二维码失败:', error);
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 获取推荐记录
const handleGetRecommendationRecords = async (req, res) => {
    try {
        const records = await getRecommendationRecords(req.user.userId);
        res.json({
            code: 200,
            data: records
        });
    } catch (error) {
        console.error('获取推荐记录失败:', error);
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 提交商家入驻申请
const handleSubmitMerchantApplication = async (req, res) => {
    try {
        console.log('[USER] 提交商家入驻申请', { 
            userId: req.user.userId, 
            role: req.user.role,
            businessName: req.body.name
        });
        
        const businessInfo = req.body;
        
        // 记录详细的请求信息
        console.log('[USER] 商家申请请求详情:', {
            userId: req.user.userId,
            role: req.user.role,
            hasName: !!businessInfo.name,
            hasAddress: !!businessInfo.address,
            hasContactPhone: !!businessInfo.contactPhone,
            hasContactPerson: !!businessInfo.contactPerson,
            hasLicenseBase64: !!businessInfo.licenseBase64,
            hasShopFrontBase64: !!businessInfo.shopFrontBase64,
            headers: {
                contentType: req.headers['content-type'],
                authorization: req.headers['authorization'] ? 'Bearer xxx...' : 'missing'
            }
        });
        
        const result = await submitMerchantApplication(req.user.userId, businessInfo);
        
        console.log('[USER] 商家入驻申请提交成功', { 
            userId: req.user.userId, 
            applicationId: result.applicationId 
        });
        
        res.json({
            code: 200,
            message: '申请提交成功',
            data: result
        });
    } catch (error) {
        console.error('[USER] 提交商家入驻申请失败:', error);
        res.status(400).json({ code: 400, message: error.message });
    }
};

// 查询商家入驻状态
const handleGetMerchantApplicationStatus = async (req, res) => {
    try {
        console.log('[USER] 查询商家入驻状态', { 
            userId: req.user.userId,
            role: req.user.role,
            path: req.path,
            headers: {
                contentType: req.headers['content-type'],
                authorization: req.headers['authorization'] ? 'Bearer xxx...' : 'missing'
            }
        });
        
        const status = await getMerchantApplicationStatus(req.user.userId);
        
        console.log('[USER] 商家入驻状态查询结果:', {
            userId: req.user.userId,
            status: status.status
        });
        
        res.json({
            code: 200,
            data: status
        });
    } catch (error) {
        console.error('[USER] 查询商家入驻状态失败:', error);
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 获取用户订单
const handleGetUserOrders = async (req, res) => {
    try {
        const { page = 1, size = 10 } = req.query;
        const orders = await getUserOrders(req.user.userId, parseInt(page), parseInt(size));
        res.json({
            code: 200,
            data: orders
        });
    } catch (error) {
        console.error('获取用户订单失败:', error);
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

// 获取订单详情
const handleGetOrderDetail = async (req, res) => {
    try {
        const { id } = req.params;
        const order = await getOrderDetail(req.user.userId, id);
        res.json({
            code: 200,
            data: order
        });
    } catch (error) {
        console.error('获取订单详情失败:', error);
        res.status(400).json({ code: 400, message: error.message });
    }
};

// 取消订单
const handleCancelOrder = async (req, res) => {
    try {
        const { id } = req.params;
        await cancelOrder(req.user.userId, id);
        res.json({
            code: 200,
            message: '订单已取消'
        });
    } catch (error) {
        console.error('取消订单失败:', error);
        res.status(400).json({ code: 400, message: error.message });
    }
};

// 确认收货
const handleConfirmReceipt = async (req, res) => {
    try {
        const { id } = req.params;
        await confirmReceipt(req.user.userId, id);
        res.json({
            code: 200,
            message: '已确认收货'
        });
    } catch (error) {
        console.error('确认收货失败:', error);
        res.status(400).json({ code: 400, message: error.message });
    }
};

// 获取用户详细信息
const getUserInfo = async (req, res) => {
    try {
        const user = await getUserById(req.user.userId);
        if (!user) {
            return res.status(404).json({ code: 404, message: '用户不存在' });
        }
        const gasCard = await getGasCardById(req.user.userId) || { balance: 0 };
        res.json({
            code: 200,
            data: {
                id: user.userId,
                nickname: user.nickname,
                avatar: user.avatar,
                gasCardBalance: gasCard.balance,
                phone: user.phone,
                realName: user.real_name,
                address: user.address
            }
        });
    } catch (error) {
        console.error('获取用户详细信息失败:', error);
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

module.exports = { getUserProfile, getMyFavorites, createFavorite, updateUserProfile, getGasCardInfo, handleRechargeGasCard, handleGetRechargeRecords, handleGetUserCoupons, handleReceiveCoupon, handleGetCouponUsageRecords, handleGetRecommendationQRCode, handleGetRecommendationRecords, handleSubmitMerchantApplication, handleGetMerchantApplicationStatus, handleGetUserOrders, handleGetOrderDetail, handleCancelOrder, handleConfirmReceipt, getUserInfo };